package com.bayair.doctor.net.exception;


import android.text.TextUtils;

import com.bayair.doctor.net.BaseEntity;

import java.io.IOException;
import java.net.SocketTimeoutException;

import retrofit2.HttpException;

/**
 * 统一处理了API异常错误
 *
 * @author xuexiang
 * @since 2018/6/20 上午1:41
 */
public class ApiException extends Exception {

    /**
     * 错误的code码
     */
    private int mCode;
    private String mMessage;

    public ApiException(String message, int code) {
        super(message);
        mCode = code;
        mMessage = message;
    }

    public int getCode() {
        return mCode;
    }

    @Override
    public String getMessage() {
        return mMessage;
    }

    /**
     * 获取错误的详细信息
     *
     * @return 获取
     */
    public String getDetailMessage() {
        return "Code:" + mCode + ", Message:" + getMessage();
    }

    public static boolean isSuccess(BaseEntity entity) {
        return entity != null && entity.isSuccess();
    }

    public static ApiException handleException(Throwable e) {
        ApiException ex;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            if (!TextUtils.isEmpty(httpException.message())) {
                ex = new ApiException(httpException.message(), httpException.code());
            } else {
                ex = new ApiException(httpException.getMessage(), httpException.code());
            }
            return ex;
        } else if (e instanceof ServerException) {
            ServerException e1 = (ServerException) e;
            ex = new ApiException(e1.getMessage(), e1.getErrCode());
            return ex;
        } else if (e instanceof DataException) {
            DataException d = (DataException) e;
            ex = new ApiException(d.getMessage(), d.getErrCode());
            return ex;
        } else if (e instanceof IOException) {
            IOException d = (IOException) e;
            String errMsg = "读写错误";
            if (d instanceof SocketTimeoutException) {
                errMsg = "连接超时";
            }
            ex = new ApiException(errMsg, ServerException.ERROR.OTHER_ERROR);
            return ex;
        } else {
            ex = new ApiException("其他错误", ServerException.ERROR.OTHER_ERROR);
            return ex;
        }
    }
}

